package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.domain.entity.*;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.FoodStockMapper;
import com.ruoyi.system.service.IFoodStockService;
import com.ruoyi.system.service.IRestaurantStoreResourceMoveService;
import com.ruoyi.system.service.ISysNoticeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @Author: ruohao
 * @Date: 2023/8/6
 **/
@Service
public class FoodStockServiceImpl implements IFoodStockService {
    private static final Logger log = LoggerFactory.getLogger(FoodStockServiceImpl.class);

    @Resource
    private FoodStockMapper foodStockMapper;

    @Resource
    ISysNoticeService sysNoticeService;

    @Resource
    IRestaurantStoreResourceMoveService restaurantStoreResourceMoveService;

    @Override
    public List<FoodStock> selectRestaurantStoreResourceList(FoodStock resource) {
        return foodStockMapper.selectRestaurantStoreResourceList(resource);
    }

    @Override
    public List<FoodStock> selectRestaurantStoreResourceListByStock(FoodStock query) {
        return foodStockMapper.selectRestaurantStoreResourceListByStock(query);
    }

    @Override
    public List<FoodStock> selectRestaurantStoreResourceListByStockOne(FoodStock query) {
        return foodStockMapper.selectRestaurantStoreResourceListByStockOne(query);
    }

    @Override
    public FoodStock selectRestaurantStoreResourceById(Long id) {
        return foodStockMapper.selectRestaurantStoreResourceById(id);
    }

    @Override
    public int insertFoodStock(FoodStock foodStock) {
        return foodStockMapper.insertRestaurantStoreResource(foodStock);
    }

    @Override
    public List<FoodStock> selectRestaurantStoreResourceByIds(List<Long> ids) {
        return foodStockMapper.selectRestaurantStoreResourceByIds(ids);
    }

    @Override
    public Boolean deleteRestaurantStoreResourceById(Long id) {
        int result = foodStockMapper.deleteRestaurantStoreResourceById(id);
        if (result == 1) {
            return Boolean.TRUE;
        }
        log.warn("删除食材到数据库失败 id {} result {}", id, result);
        return Boolean.FALSE;
    }

    @Override
    public int deleteRestaurantStoreResourceByIds(List<Long> ids) {
        log.info("deleteRestaurantStoreResourceByIds ids {}", JSON.toJSONString(ids));
        return foodStockMapper.deleteRestaurantStoreResourceByIds(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStockById(String area, Long resourceId, BigDecimal amount, BigDecimal storeAmount) {
        if (StringUtils.isBlank(area) || (!area.equals("二区") && !area.equals("一区"))) {
            throw new BaseException("园区错误,不能用同时属于多个园区的人创建业务" + area);
        }
        FoodStock query = FoodStock.builder().area(area).resourceId(resourceId).build();//根据食材id和地区去找库存
        FoodStock resource = foodStockMapper.selectRestaurantStoreResource(query);
        if (resource == null) {
            throw new BaseException("修改失败,未找到库存记录" + resourceId + "-" + area);
        }
        resource.setAmount(amount);
        resource.setLastAmount(storeAmount);
        foodStockMapper.updateRestaurantStoreResource(resource);

        //是否触发预警
        sysNoticeService.createNewRecord(resource);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStockByOut(StoreOut storeOut, List<StoreOutDetail> details) {
        for (StoreOutDetail detail : details) {
            if (StringUtils.isBlank(storeOut.getArea()) || (!storeOut.getArea().equals("二区") && !storeOut.getArea().equals("一区"))) {
                throw new BaseException("园区错误,不能用同时属于多个园区的人创建业务" + storeOut.getArea());
            }
            FoodStock query = FoodStock.builder().area(storeOut.getArea()).resourceId(detail.getResourceId()).build();//根据食材id和地区去找库存
            FoodStock resource = foodStockMapper.selectRestaurantStoreResource(query);
            if (resource == null) {
                throw new BaseException("修改失败,未找到库存记录" + detail.getResourceId() + "-" + storeOut.getArea());
            }
            if (resource.getAmount().compareTo(detail.getAmount()) == -1) {
//            if (resource.getAmount() - detail.getAmount() < 0) {
                throw new BaseException("出库失败," + resource.getName() + "库存当前为" + resource.getAmount() + ",小于出库数量" + detail.getAmount());
            }
            resource.setAmount(resource.getAmount().subtract(detail.getAmount()));
            foodStockMapper.updateRestaurantStoreResource(resource);

            //记录移动明细
            RestaurantStoreResourceMove move = new RestaurantStoreResourceMove();
            move.setAmount(detail.getAmount());
            move.setResourceId(detail.getResourceId());
            move.setBusinessNum(storeOut.getId().toString());
            move.setBusinessType(storeOut.getType());
            move.setUnit(detail.getUnit());
            move.setArea(storeOut.getArea());
            restaurantStoreResourceMoveService.insertRestaurantStoreResourceMove(move);

            //是否触发预警
            sysNoticeService.createNewRecord(resource);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStockByIn(StoreIn storeIn, List<StoreInDetail> details) {
        for (StoreInDetail detail : details) {
            if (StringUtils.isBlank(storeIn.getArea()) || (!storeIn.getArea().equals("二区") && !storeIn.getArea().equals("一区"))) {
                throw new BaseException("园区错误,不能用同时属于多个园区的人创建业务" + storeIn.getArea());
            }
            FoodStock query = FoodStock.builder().area(storeIn.getArea()).resourceId(detail.getResourceId()).build();//根据食材id和地区去找库存
            FoodStock resource = foodStockMapper.selectRestaurantStoreResource(query);
            if (resource == null) {
                throw new BaseException("修改失败,未找到库存记录" + detail.getResourceId() + "-" + storeIn.getArea());
            }
            resource.setAmount(resource.getAmount().add(detail.getAmount()));
            resource.setGuarantee(storeIn.getConfirmTime() == null ? new Date() : storeIn.getConfirmTime());
            foodStockMapper.updateRestaurantStoreResource(resource);

            //记录移动明细
            RestaurantStoreResourceMove move = new RestaurantStoreResourceMove();
            move.setAmount(detail.getAmount());
            move.setResourceId(detail.getResourceId());
            move.setBusinessNum(storeIn.getId().toString());
            move.setBusinessType(storeIn.getType());
            move.setUnit(detail.getUnit());
            move.setArea(storeIn.getArea());
            restaurantStoreResourceMoveService.insertRestaurantStoreResourceMove(move);

            //是否触发预警
            sysNoticeService.createNewRecord(resource);
        }
    }
}
